import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Cascader,
	Tabs,
	TreeSelect,
	message,
	Spin,
	Select,
} from 'antd'
import React, {useEffect, useState} from 'react'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import BasicInformation from './components/BasicInformation'
import BankInformation from './components/BankInformation'
import Qualification from './components/Qualification'
import Bidding from './components/Bidding'
import Settlement from './components/Settlement'
import Purchase from './components/Purchase'
import Contract from './components/Contract'
import Grade from './components/Grade'
import Exit from './components/Exit'
import {getDict} from '@/service/common/dict'
import {getSupplierType, translateDataToTree} from '@/utils/common'
import {supplierArchivesInfo} from '@/service/supplier/supplierArchives'
import {getAllCitys, getCompany, getSupAndSubCompany} from '@/service/common'
import {getformDatas} from './data'
import {getPublicDownloadUrl} from '@/service/common/upload'
import {getUrls} from '@/pages/supplier/admittance/child/add/data'
import {getSubjectCompany} from '@/service/merchantCenter/clue'
import OperationRecord from '@/components/OperationRecord'

const {TextArea} = Input
const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}
// 城市
const cityNames = {
	label: 'name',
	value: 'id',
	children: 'cityInfoList',
}

const details = (props: any) => {
	const {query} = props.location
	const [form] = Form.useForm()
	const [tabItem, setTabItem] = useState<any[]>([])
	const [dataSource, setDataSource] = useState<any>()
	// 字典数据
	const [dictData, setDictData] = useState<any>({})
	const [supplierTypeData, setSupplierTypeData] =
		useState<supplierAPI.supplierType>([])
	const [allCompanyData, setAllCompanyData] = useState([])
	const [companyData, setCompanyData] = useState<any>()
	const [loading, setLoading] = useState(false)
	const [enclosureList, setEnclosureList] = useState<any[]>([])
	// 城市数据
	const [citysList, setCitysList] = useState([])
	const [supplierType, setSupplierType] = useState<any[]>([]) // 供应商类型
	const [mainBodyData, setMainBodyData] = useState([]) // 主体数据
	/** 获取主体数据 */
	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.success) {
				setMainBodyData(res.data.data)
			}
		})
	}
	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res.data)
			}
		})
	}

	// 获取档案详情
	const getData = () => {
		setLoading(true)
		supplierArchivesInfo(query?.id)
			.then((res: any) => {
				if (res?.success) {
					setLoading(false)
					setDataSource(res.data)
					let urlDatas: any = {}
					const newSupplierType = res.data?.supplierType?.split(',')
					setSupplierType(newSupplierType)
					const admittanceData = {
						...res.data,
						examineOrgId: res?.data?.supplierBase?.examineOrgId,
						supplierType: res.data?.supplierType?.split(','),
						orgId:
							newSupplierType?.[0] === 'SP_GYS' ||
							newSupplierType?.[0] === 'CS_GYS'
								? res?.data?.orgId
								: res?.data?.orgId?.split(',').map(Number),
					}

					if (newSupplierType?.[0] === 'SP_GYS') {
						urlDatas = res.data?.spInfo
						admittanceData.city = [
							urlDatas?.provinceId,
							urlDatas?.cityId,
						]
					} else if (newSupplierType?.[0] === 'DYY_GYS') {
						urlDatas = res.data?.assetInfo
					} else if (
						newSupplierType[0] === 'CZ_GYS' &&
						newSupplierType[1] === '32'
					) {
						urlDatas = res.data?.handle
					} else {
						urlDatas = res.data?.supplierBase
					}
					if (newSupplierType?.[0] === 'CS_GYS') {
						admittanceData.city = [
							res.data?.supplierBase?.provinceId,
							res.data?.supplierBase?.cityId,
						]
					}
					form.setFieldsValue(admittanceData)
					const url = getUrls(urlDatas, newSupplierType?.[0])?.filter(
						(item) => item !== 0,
					)
					if (url?.length) {
						getPublicDownloadUrl(url)
							.then((result: any) => {
								if (result?.success) {
									setEnclosureList(result?.data)
								}
							})
							.catch((err: any) => {
								message.error(err)
							})
					}
					form.setFieldsValue({})
				}
			})
			.catch((err) => {
				message.error(err)
				setLoading(false)
			})
	}

	/** 获取所有公司数据 */
	const onAllCompany = () => {
		getSupAndSubCompany().then((res: any) => {
			const list = translateDataToTree(res.data)
			setAllCompanyData(list as any)
		})
	}
	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: props.user.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		// 初始化字典数据
		getDict(
			{
				dictKeys: [
					'ZC_GYS',
					'JC_GYS',
					'CZ_GYS',
					'SP_GYS',
					'DYY_GYS',
					'CS_GYS',
					'Rating_Cycle',
					'Enterprise_Nature',
					'Invoicing_Tax_Rate',
					'Term_Payment',
					'Agency_Business',
					'Cooperation_Mode',
					'Business_Model',
					'Company_Type',
					'Channel_Type',
					'Settlement_Cycle',
					'Nature_Contract',
					'Contract_Status',
					'Business_Situation',
					'Supplier_Rating',
					'Project_Bid_Section',
					'Project_Status',
					'Category',
					'SP_Settlement_Method',
					'CS_Settlement_Method',
				],
			},
			(res: any) => {
				setDictData(res)
				// 组装供应商类型
				const newData = getSupplierType([
					res.ZC_GYS,
					res.JC_GYS,
					res.CZ_GYS,
					res.SP_GYS,
					res.DYY_GYS,
					res.CS_GYS,
				])
				setSupplierTypeData(newData)
			},
		)
		getData()
		onAllCompany()
		onCompany()
		getCitysFun()
		getSubjectFun()
	}, [])

	useEffect(() => {
		if (dataSource) {
			let basicsData
			if (dataSource?.spInfo) {
				const newData = {...dataSource.spInfo, gysType: 'sp'}
				basicsData = {
					...newData,
					city: newData?.cityId
						? [newData?.provinceId, newData?.cityId]
						: [],
				}
			} else if (dataSource?.handle) {
				const newData = {...dataSource.handle, gysType: 'cz'}
				basicsData = {
					...newData,
					city: newData?.cityId
						? [newData?.provinceId, newData?.cityId]
						: [],
					establishDate: moment(newData?.establishDate),
					automobileBusinessTime: moment(newData?.establishDate),
					headquarters: newData?.headquarters
						?.split(',')
						?.map(Number),
				}
			} else if (dataSource?.supplierBase) {
				const data = getformDatas(dataSource)
				if (dataSource?.supplierType === 'CS_GYS') {
					basicsData = {...data.basicsValue, gysType: 'cs'}
				} else {
					basicsData = {...data.basicsValue, gysType: 'other'}
				}
			}
			const item = [
				{
					label: '资质信息',
					key: '资质信息',
					children: (
						<Qualification
							enclosureList={enclosureList}
							type={dataSource?.supplierType}
						/>
					),
				},
				{
					label: '招投标信息',
					key: '招投标信息',
					children: <Bidding data={dataSource} dictData={dictData} />,
				},
				{
					label: '合同信息',
					key: '合同信息',
					children: <Contract supplierId={query?.id} />,
				},
				{
					label: '采购信息',
					key: '采购信息',
					children: <Purchase supplierId={query?.id} />,
				},
				{
					label: '结算信息',
					key: '结算信息',
					children: <Settlement supplierId={query?.id} />,
				},
				{
					label: '评级信息',
					key: '评级信息',
					children: (
						<Grade
							data={dataSource}
							dictData={dictData}
							supplierTypeData={supplierTypeData}
						/>
					),
				},
				{
					label: '准出信息',
					key: '准出信息',
					children: (
						<Exit
							dataSource={dataSource}
							supplierTypeData={supplierTypeData}
							companyData={companyData}
							contactPhone={query?.contactPhone}
						/>
					),
				},
				{
					label: '操作记录',
					key: '操作记录',
					children: (
						<OperationRecord
							businessId={query?.id}
							businessType={40}
						/>
					),
				},
			]
			if (!dataSource?.assetInfo) {
				item.splice(
					0,
					0,
					{
						label: '基础信息',
						key: '基础信息',
						children: (
							<BasicInformation
								data={basicsData}
								dictData={dictData}
								citysList={citysList}
							/>
						),
					},
					{
						label: '银行信息',
						key: '银行信息',
						children: (
							<BankInformation
								data={dataSource}
								citysList={citysList}
							/>
						),
					},
				)
			}
			setTabItem(item)
		}
	}, [
		dictData,
		dataSource,
		enclosureList,
		supplierTypeData,
		companyData,
		citysList,
	])
	const types =
		supplierType[0] !== 'DYY_GYS' &&
		supplierType[0] !== 'SP_GYS' &&
		supplierType[0] !== 'CS_GYS' &&
		supplierType?.[1] !== '32'
	return (
		<Spin spinning={loading}>
			<div className={styles.admittanceDetails}>
				<div className={styles.header}>
					<Form
						form={form}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled>
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="统一社会信用代码"
									name="socialCreditCode">
									<Input placeholder="-" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商名称"
									name="supplierName">
									<Input placeholder="-" />
								</Form.Item>
							</Col>
							{supplierType?.[0] === 'SP_GYS' ||
							supplierType?.[0] === 'CS_GYS' ? (
								''
							) : (
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="供应商简称"
										name="abbreviation">
										<Input placeholder="-" />
									</Form.Item>
								</Col>
							)}

							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商简称"
									name="abbreviation">
									<Input placeholder="-" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商编号"
									name="supplierCode">
									<Input placeholder="-" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="创建人"
									name="supplierCreator">
									<Input placeholder="-" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商类型"
									name="supplierType"
									colon>
									<Cascader options={supplierTypeData} />
								</Form.Item>
							</Col>
							{types ? (
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="审核采购组织"
										name="examineOrgId">
										<TreeSelect
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											treeNodeFilterProp="name"
											treeDefaultExpandAll
											fieldNames={fieldNames}
											treeDataSimpleMode
											treeData={allCompanyData}
										/>
									</Form.Item>
								</Col>
							) : (
								''
							)}
							{supplierType?.[0] === 'SP_GYS' ||
							supplierType?.[0] === 'CS_GYS' ? (
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item label="主体" name="subject">
										<Select
											placeholder="请选择"
											fieldNames={{
												label: 'merchantName',
												value: 'id',
											}}
											options={mainBodyData}
										/>
									</Form.Item>
								</Col>
							) : (
								''
							)}
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item label="所属公司" name="orgId">
									<TreeSelect
										style={{width: '100%'}}
										dropdownStyle={{
											maxHeight: 400,
											overflow: 'auto',
										}}
										allowClear
										multiple={
											!(
												supplierType?.[0] ===
													'SP_GYS' ||
												supplierType?.[0] === 'CS_GYS'
											)
										}
										showCheckedStrategy="SHOW_ALL"
										treeDefaultExpandAll
										treeNodeFilterProp="name"
										fieldNames={{
											label: 'name',
											value: 'id',
										}}
										treeDataSimpleMode
										treeData={companyData}
									/>
								</Form.Item>
							</Col>
							{supplierType?.[0] === 'SP_GYS' ||
							supplierType?.[0] === 'CS_GYS' ? (
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item label="城市" name="city">
										<Cascader
											fieldNames={cityNames}
											options={citysList}
										/>
									</Form.Item>
								</Col>
							) : (
								''
							)}
							<Col span={24}>
								<Form.Item label="引入原因" name="reason">
									<TextArea
										maxLength={200}
										placeholder="请输入（最多200个字）"
										autoSize={{minRows: 2, maxRows: 6}}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</div>
				<div className={styles.content}>
					<Tabs
						type="card"
						defaultActiveKey="基础信息"
						items={tabItem}
					/>
				</div>
				<Button
					className={styles.btn}
					onClick={() => {
						history.go(-1)
					}}>
					返回
				</Button>
			</div>
		</Spin>
	)
}
export default connect(({user}: any) => ({user}))(details)
